package database

import (
	"gitee.com/eqyun/gosdk/config"
	"gitee.com/eqyun/gosdk/sdk"
	"gitee.com/eqyun/gosdk/sdk/core/global"
	"gitee.com/eqyun/gosdk/sdk/pkg"
	"gitee.com/eqyun/gosdk/sdk/tools/database"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"time"
)

func Setup() {
	for k := range config.DatabasesConfig {
		setupSimpleDatabase(k, config.DatabasesConfig[k])
	}
}

func setupSimpleDatabase(host string, c *config.Database) {
	if global.Driver == "" {
		global.Driver = c.Driver
	}
	registers := make([]database.ResolverConfigure, len(c.Registers))
	for i := range c.Registers {
		registers[i] = database.NewResolverConfigure(
			c.Registers[i].Sources,
			c.Registers[i].Replicas,
			c.Registers[i].Policy,
			c.Registers[i].Tables)
	}
	resolverConfig := database.NewConfigure(c.Source, c.MaxIdleConns, c.MaxOpenConns, c.ConnMaxIdleTime, c.ConnMaxLifeTime, registers)

	lconfig := logger.Config{
		SlowThreshold:             time.Second,  // 慢 SQL 阈值
		LogLevel:                  logger.Error, // 日志级别
		IgnoreRecordNotFoundError: true,         // 忽略ErrRecordNotFound（记录未找到）错误
		Colorful:                  true,         // 禁用彩色打印
	}
	if c.ShowSql {
		lconfig.LogLevel = logger.Info
	}

	db, err := resolverConfig.Init(&gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		Logger: logger.New(
			log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
			lconfig,
		),
	}, opens[c.Driver])
	if err != nil {
		log.Fatal(pkg.Red(c.Driver+" connect error :"), err)
	} else {
		log.Println(pkg.Green(c.Driver + " connect success !"))
	}
	//db.Logger.LogMode(logger.Info)
	sdk.Runtime.SetDb(host, db)
	/*if global.Driver == "" {
		global.Driver = c.Driver
	}*/
	/*log.Infof("%s => %s", host, pkg.Green(c.Source))
	registers := make([]c.ResolverConfigure, len(c.Registers))
	for i := range c.Registers {
		registers[i] = toolsDB.NewResolverConfigure(
			c.Registers[i].Sources,
			c.Registers[i].Replicas,
			c.Registers[i].Policy,
			c.Registers[i].Tables)
	}
	resolverConfig := toolsDB.NewConfigure(c.Source, c.MaxIdleConns, c.MaxOpenConns, c.ConnMaxIdleTime, c.ConnMaxLifeTime, registers)
	db, err := resolverConfig.Init(&gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		Logger: New(
			logger.Config{
				SlowThreshold: time.Second,
				Colorful:      true,
				LogLevel: logger.LogLevel(
					log.DefaultLogger.Options().Level.LevelForGorm()),
			},
		),
	}, opens[c.Driver])

	if err != nil {
		log.Fatal(pkg.Red(c.Driver+" connect error :"), err)
	} else {
		log.Info(pkg.Green(c.Driver + " connect success !"))
	}

	e := mycasbin.Setup(db, "")*/
	//x, err := xorm.NewEngine(c.Driver, c.Source)
	//if err != nil {
	//fmt.Println(err)
	//}
	//x.SetMaxIdleConns(c.MaxIdleConns)
	//x.SetMaxOpenConns(c.MaxOpenConns)
	// 同步结构体与数据表
	//if err = x.CreateTables(new(lottery.LotteryResult)); err != nil {
	//	log.Fatalf("Fail to sync database: %v\n", err)
	//	}
	//x.SetLogLevel(log.LOG_DEBUG)
	//x.ShowSQL(c.ShowSql)
}
